package com.jyw.business.de.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.jyw.business.de.constant.DemandAllocationTypeConstant;
import com.jyw.business.de.constant.DemandProcessConstant;
import com.jyw.business.de.constant.DemandStateConstant;
import com.jyw.business.de.domain.DeDemandInfo;
import com.jyw.business.de.domain.dto.web.DemandAllocationDto;
import com.jyw.business.de.domain.dto.web.TransferDto;
import com.jyw.business.de.domain.vo.web.DemandAllocationConfig;
import com.jyw.business.de.domain.vo.web.DemandTypeAllocationUser;
import com.jyw.business.de.service.*;
import com.jyw.common.exception.ServiceException;
import com.jyw.common.utils.DateUtils;
import com.jyw.common.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import com.jyw.business.de.mapper.DeDemandAllocationMapper;
import com.jyw.business.de.domain.DeDemandAllocation;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * 需求-需求分配记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-02-21
 */
@Service
public class DeDemandAllocationServiceImpl extends ServiceImpl<DeDemandAllocationMapper,DeDemandAllocation> implements IDeDemandAllocationService
{
    @Resource
    private DeDemandAllocationMapper deDemandAllocationMapper;

    @Resource
    private ISysDemandAllocationConfigService allocationConfigService;

    @Resource
    private IDeDemandInfoService deDemandInfoService;

    @Resource
    private IDeDemandProcessService processService;

    /**
     * 查询需求-需求分配记录
     * 
     * @param id 需求-需求分配记录主键
     * @return 需求-需求分配记录
     */
    @Override
    public DeDemandAllocation selectDeDemandAllocationById(Long id)
    {
        return deDemandAllocationMapper.selectDeDemandAllocationById(id);
    }

    /**
     * 查询需求-需求分配记录列表
     * 
     * @param deDemandAllocation 需求-需求分配记录
     * @return 需求-需求分配记录
     */
    @Override
    public List<DeDemandAllocation> selectDeDemandAllocationList(DeDemandAllocation deDemandAllocation)
    {
        return deDemandAllocationMapper.selectDeDemandAllocationList(deDemandAllocation);
    }

    /**
     * 新增需求-需求分配记录
     * 
     * @param deDemandAllocation 需求-需求分配记录
     * @return 结果
     */
    @Override
    public int insertDeDemandAllocation(DeDemandAllocation deDemandAllocation)
    {
        deDemandAllocation.setCreateTime(DateUtils.getNowDate());
        return deDemandAllocationMapper.insertDeDemandAllocation(deDemandAllocation);
    }

    /**
     * 修改需求-需求分配记录
     * 
     * @param deDemandAllocation 需求-需求分配记录
     * @return 结果
     */
    @Override
    public int updateDeDemandAllocation(DeDemandAllocation deDemandAllocation)
    {
        return deDemandAllocationMapper.updateDeDemandAllocation(deDemandAllocation);
    }

    /**
     * 批量删除需求-需求分配记录
     * 
     * @param ids 需要删除的需求-需求分配记录主键
     * @return 结果
     */
    @Override
    public int deleteDeDemandAllocationByIds(Long[] ids)
    {
        return deDemandAllocationMapper.deleteDeDemandAllocationByIds(ids);
    }

    /**
     * 删除需求-需求分配记录信息
     * 
     * @param id 需求-需求分配记录主键
     * @return 结果
     */
    @Override
    public int deleteDeDemandAllocationById(Long id)
    {
        return deDemandAllocationMapper.deleteDeDemandAllocationById(id);
    }

    @Override
    public boolean autoAllocation(Long demandId) {
        //获取需求信息
        DeDemandInfo info = deDemandInfoService.getById(demandId);
        //获取需求自动分配配置
        DemandAllocationConfig config = allocationConfigService.getConfig();
        //开启了自动分配
        if(config.getOpen()){
            Long userId = null;
            try{
                //有可能定时任务无法获取登陆人
                userId = SecurityUtils.getUserId();
            }catch (Exception e){
                log.warn("自动分配,获取登陆人失败");
            }
            //获取需求类型分配配置
            DemandTypeAllocationUser demandTypeAllocationUser = config.getDemandConfig().stream().filter(data -> data.getDictValue().equals(info.getDemandType())).findFirst().orElse(null);
            //判断是否配置了分配人员
            if(!ObjectUtils.isEmpty(demandTypeAllocationUser)&&!CollectionUtils.isEmpty(demandTypeAllocationUser.getUsers())){
                Long finalUserId = userId;
                demandTypeAllocationUser.getUsers().forEach(data->{
                    //循环分配需求负责人
                    DeDemandAllocation deDemandAllocation = new DeDemandAllocation();
                    deDemandAllocation.setDemandId(demandId);
                    deDemandAllocation.setAllocationUser(data);
                    deDemandAllocation.setCreateUser(finalUserId);
                    deDemandAllocation.setCreateTime(DateUtils.getNowDate());
                    save(deDemandAllocation);
                });
                //记录分配操作流程
                processService.saveProcess(demandId,
                        DemandProcessConstant.ALLOCATION,
                        demandTypeAllocationUser.getUsers().stream().map(user->user.toString()).collect(Collectors.joining(",")),
                        userId);
                //修改需求状态为待接收
                deDemandInfoService.updateById(
                        new DeDemandInfo(){{setId(demandId);
                        setDemandState(DemandStateConstant.ACCEPT);
                        setWaitAcceptTime(DateUtils.getNowDate());
                        }}
                );
                return true;
            }
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void allocation(DemandAllocationDto dto) {
        //获取需求
        DeDemandInfo info = deDemandInfoService.getById(dto.getId());
        if(ObjectUtils.isEmpty(info)){
            throw new ServiceException("需求不存在");
        }
        if(!info.getDemandState().equals(DemandStateConstant.ALLOCATION)){
            throw new ServiceException("需求状态不为待分配,无法分配需求");
        }
        //判断需求分配类型
        if(DemandAllocationTypeConstant.ALLOCATION_MINE.equals(dto.getAllocationType())){
            //由我处理,设置分配人为自己
            dto.setUserId(SecurityUtils.getUserId());
        }
        //新建分配需求记录
        DeDemandAllocation deDemandAllocation = new DeDemandAllocation();
        deDemandAllocation.setDemandId(dto.getId());
        deDemandAllocation.setAllocationUser(dto.getUserId());
        deDemandAllocation.setCreateUser(SecurityUtils.getUserId());
        deDemandAllocation.setCreateTime(DateUtils.getNowDate());
        save(deDemandAllocation);
        //记录分配流程
        processService.saveProcess(dto.getId(),
                DemandProcessConstant.ALLOCATION,
                dto.getUserId());
        //修改状态为需求待接收
        deDemandInfoService.updateById(new DeDemandInfo(){{
            setId(dto.getId());
            setDemandState(DemandStateConstant.ACCEPT);
            setWaitAcceptTime(DateUtils.getNowDate());
        }});
        //判断是否是由我处理,如果是那么自动接收
        if(DemandAllocationTypeConstant.ALLOCATION_MINE.equals(dto.getAllocationType())){
            deDemandInfoService.acceptDemand(dto.getId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transferAllocation(TransferDto dto) {
        //删除之前的分配信息
        lambdaUpdate()
                .eq(DeDemandAllocation::getDemandId,dto.getId())
                .remove();
        //新增分配信息
        DeDemandAllocation allocation = dto.buildAllocation();
        save(allocation);
    }
}
